<template>
	<div class="content">
		<div class="pageSearchView">
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<el-form-item label="任务单号">
					<el-input v-model="searchParam.code" placeholder="请输入任务单号" clearable style="width: 200px" />
				</el-form-item>
				<el-form-item label="出库仓库">
					<el-tree-select v-model="searchParam.wareOutId" :data="wareList" clearable filterable check-strictly
													placeholder="请选择出库仓库" :render-after-expand="false" :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 180px" @change="wareChangeOut" />
				</el-form-item>
				<el-form-item label="出库库位">
					<el-select v-model="searchParam.sourceStorageId" multiple collapse-tags collapse-tags-tooltip
										 max-collapse-tags="1" clearable filterable placeholder="请选择出库库位"
										 style="width: 180px">
						<el-option v-for="item in storageOutList" :key="item.id" :label="item.storageName"
											 :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="入库仓库">
					<el-tree-select v-model="searchParam.wareId" :data="wareList" check-strictly clearable filterable
													placeholder="请选择入库仓库" :render-after-expand="false" :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 180px" @change="wareChange" />
				</el-form-item>
				<el-form-item label="入库库位">
					<el-select v-model="searchParam.targetStorageId" multiple collapse-tags collapse-tags-tooltip
										 max-collapse-tags="1" clearable filterable placeholder="请选择入库库位"
										 style="width: 180px">
						<el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
											 :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="单据状态" prop="businessType">
					<el-select v-model="searchParam.statusCodes" multiple filterable placeholder="请选择单据状态" style="width: 220px">
						<el-option :key="1" label="待处理"
											 :value="1" />
						<el-option :key="2" label="进行中"
											 :value="2" />
						<el-option :key="3" label="完结"
											 :value="3" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
					<el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>列表信息</div>
				</div>
				<div class="pageTableButView">
					<el-button  type="primary" @click="handleAdd" :icon="Plus">新建</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table :data="paginatedData" height="calc(100vh - 320px)" row-key="id" :stripe="false"
								header-cell-class-name="witheTableHeader" @expand-change="handleExpandChange">
				<el-table-column type="expand">
					<template #default="scope">
						<!--            子级列表-->
						<div m="4">
							<el-table ref="tableCil" :stripe="false" border size="small" :data="scope.row.children"
												style="width: 95%;margin-left: 20px" header-cell-class-name="blueTableHeader">
								<el-table-column type="index" width="80" label="" align="center" />
								<el-table-column label="物料名称" prop="materialName" min-width="150" align="center"
																 show-overflow-tooltip />
								<el-table-column type label="需求数量" prop="materialCount" min-width="150" align="center"
																 show-overflow-tooltip />
								<el-table-column label="实际出库数量" prop="actualOutCount" min-width="150" align="center"
																 show-overflow-tooltip />
								<el-table-column label="" min-width="80" align="center"
																 v-if="scope.row.allotStatus != 3">
									<template #default="scopes">
										<el-button type="text" size="small" :icon="Files
											" @click="doOutIn(scopes.row)" v-if="scope.row.allotStatus != 3">出库
										</el-button>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="序号" align="center" width="70">
					<template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
				</el-table-column>
				<el-table-column label="任务单号" prop="code" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="工序订单号" prop="procedureOrderNo" min-width="150" show-overflow-tooltip
												 align="center" />
				<el-table-column label="业务类型" prop="transferType" :formatter="transferTypeFormatter" min-width="100"
												 show-overflow-tooltip align="center" />
				<el-table-column label="出库库位" prop="sourceStorageName" min-width="150" show-overflow-tooltip
												 align="center" />
				<el-table-column label="入库库位" prop="targetStorageName" min-width="150" show-overflow-tooltip
												 align="center" />
				<!--				<el-table-column label="创建人" prop="createUser" min-width="150" show-overflow-tooltip align="center" />-->
				<el-table-column label="创建时间" prop="createTime" min-width="150" show-overflow-tooltip align="center" />
				<!--        <el-table-column prop="status" label="状态" width="100">-->
				<!--          <template #default="scope">-->
				<!--            {{ scope.row.status === 0 ? '未完成' : '已完成' }}-->
				<!--          </template>-->
				<!--        </el-table-column>-->
				<el-table-column prop="allotStatus" align="center" min-width="80" label="单据状态"
												 :formatter="formatStatus" />
				<el-table-column label="操作" width="200" align="center" fixed="right">
					<template #default="scope">
						<el-button type="text" size="small" :icon="Tickets"
											 @click="handleEdit(scope.row, 1)">详情
						</el-button>
						<el-button type="text" size="small" :icon="DocumentChecked
							" @click="doFinish(scope.row)" v-if="scope.row.allotStatus != 3">完结
						</el-button>
						<!--            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
						<!--            <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button>-->
					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
											 :current-page="currentPage" @size-change="handleSizeChange"
											 @current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 编辑/新建弹框 -->
		<el-dialog v-model="showCrud" :title="crudTitle + '备料单'" width="1000px">
			<el-form ref="formRef" :model="formData" label-width="100px" :rules="outInRules">
				<el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="工序订单" prop="procedureOrderId" required>
							<el-select v-model="formData.procedureOrderId" placeholder="请选择工序订单" clearable filterable
												 style="width: 180px" :disabled="popType == 1">
								<el-option v-for="item in procedureOrderList" :key="item.id" :label="item.no"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="出库仓库">
							<el-tree-select v-model="formData.wareOutId" :data="wareList" :disabled="popType == 1"
															check-strictly clearable filterable :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" style="width: 180px" @change="wareChangeOut" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="出库库位" prop="sourceStorageId" required>
							<el-select v-model="formData.sourceStorageId" clearable filterable :disabled="popType == 1"
												 placeholder="请选择" style="width: 180px">
								<el-option v-for="item in storageOutList" :key="item.id" :label="item.storageName"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="入库仓库">
							<el-tree-select v-model="formData.wareId" :data="wareList" :disabled="popType == 1"
															check-strictly clearable filterable :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" style="width: 180px" @change="wareChange" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="入库库位" prop="targetStorageId" required>
							<el-select v-model="formData.targetStorageId" clearable filterable :disabled="popType == 1"
												 placeholder="请选择" style="width: 180px">
								<el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<div class="pageTableTitle">物料列表</div>
				</el-row>
				<el-row :gutter="10" style="padding: 10px">
					<el-table :data="formData.details" style="width:100% " height="300px">
						<el-table-column label="序号" type="index" align="center" width="80" />
						<el-table-column prop="materialId" label="物料编码" align="center">
							<template #default="scope">
								<el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder=""
													 clearable filterable>
									<el-option v-for="item in materiaList" :key="item.value" :label="item.label"
														 :value="item.value" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="materialCount" label="数量" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.materialCount" type="number" :disabled="popType == 1"
													placeholder=""></el-input>
							</template>
						</el-table-column>
						<!--            <el-table-column-->
						<!--                prop="batchNo"-->
						<!--                label="批次号"-->
						<!--                align="center"-->
						<!--            >-->
						<!--              <template #default="scope">-->
						<!--                <el-input v-model="scope.row.batchNo" placeholder="" :disabled="popType == 1"-->
						<!--                          style="width: 100%"></el-input>-->
						<!--              </template>-->
						<!--            </el-table-column>-->
						<el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
							<template #header>
								<el-button :icon="Plus" text @click="handleAddConfigLine">新建</el-button>
							</template>
							<template #default="scope">
								<!--                <el-button @click="handleEditConfigLine(scope.row,scope.$index)"-->
								<!--                           plain :icon="Edit">-->
								<!--                  编辑-->
								<!--                </el-button>-->
								<el-button type="danger" text :icon="Delete" @click="handleConfigDelete(scope.$index)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(formRef)">保存</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 查看详情弹框 -->
		<el-dialog v-model="showDetail" :title="crudTitle + '备料单'" width="90%">
			<el-form :model="formData" label-width="100px">
				<el-row :gutter="10">
					<el-col :span="6">
						<el-form-item label="工序订单："> {{ formData.procedureOrderName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="出库仓库："> {{ formData.sourceWarehouseName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="出库库位："> {{ formData.sourceStorageName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="入库仓库："> {{ formData.targetWarehouseName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="入库库位："> {{ formData.targetStorageName || '--' }}</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<div class="pageTableTitle">物料列表</div>
				</el-row>
				<el-row :gutter="10" style="padding: 10px">
					<el-table :data="formData.tasks" style="width:100% " height="300px">
						<el-table-column label="序号" type="index" align="center" width="80" />
						<el-table-column prop="materialName" label="物料名称" align="center" />
						<el-table-column prop="materialCount" label="已出库数量" align="center" width="150" />
						<el-table-column prop="batchNo" label="批次号" align="center" />
						<el-table-column prop="status" label="任务状态" align="center" :filters="[
        { text: '已确认入库', value: '3' },
        { text: '未确认入库', value: '2' },
      ]"
														 :filter-method="filterTag"
														 filter-placement="bottom-end" width="150">
							<template #default="scope">
								{{ scope.row.status == 2 ? '未确认入库' : '已确认入库' }}
							</template>
						</el-table-column>
						<el-table-column prop="createTime" label="创建时间" align="center" />
						<el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
							<template #header>
								<el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
							</template>
							<template #default="scope">
								<el-button type="danger" plain :icon="Delete" @click="handleConfigDelete(scope.$index)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showDetail = false">关闭</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 点击入库弹窗 -->
		<el-dialog v-model="showOutIn" title="出库" width="85%">
			<el-form :model="outInForm" :rules="outInRules" ref="outInFormRef" label-width="100px">
				<el-row :gutter="10">
					<el-col :span="6">
						<el-form-item label="物料名称"> {{ outInForm.materialName || '--' }}</el-form-item>
					</el-col>
					<!--          <el-col :span="8">-->
					<!--            <el-form-item label="批次号" prop="batchNo" required>-->
					<!--              <el-input v-model="outInForm.batchNo" placeholder=""></el-input>-->
					<!--            </el-form-item>-->
					<!--          </el-col>-->
					<el-col :span="6">
						<el-form-item label="数量" prop="materialCount" required>
							<el-input v-model="outInForm.materialCount" type="number" placeholder=""></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="出库仓库">
							<el-tree-select v-model="outInForm.wareOutId" :data="wareList" check-strictly clearable
															filterable :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="wareChangeOut" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="出库库位" prop="sourceStorageId">
							<el-select v-model="outInForm.sourceStorageId" clearable filterable placeholder="请选择"
												 @change="getWorkNO(outInForm.materialId, outInForm.sourceStorageId)">
								<el-option v-for="item in storageOutList" :key="item.id" :label="item.storageName"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="入库仓库">
							<el-tree-select v-model="outInForm.targetWarehouseId" :data="wareList" check-strictly
															:render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="wareChange" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="入库库位" prop="targetStorageId" required>
							<el-select v-model="outInForm.targetStorageId" placeholder="请选择">
								<!--                sourceStorageId-->
								<el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="批次号" required prop="batchNo">
							<el-select v-model="outInForm.batchNo" placeholder="请选择批次" clearable filterable
												 @change="batchNoChange">
								<el-option v-for="item in batchNoList" :key="item.id" :label="item.batchNo"
													 :value="item.batchNo">
									<span style="float: left;padding-right: 10px;color: #333">{{ item.batchNo }}</span>
									<span style="float: right;color: #999;font-size: 13px;"> 数量：{{ item.count }} </span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="批次"> {{ outInForm.batch || '--' }}</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showOutIn = false">取消</el-button>
					<el-button type="primary" @click="outInSum(outInFormRef)">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {
	Delete, Edit, Tickets, DocumentChecked
	, Search, Share, Upload, Refresh, Plus, DocumentCopy, Files
} from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';


const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const handleSizeChange = (val) => {
	pageSize.value = val;
	getList();
};
const handleCurrentChange = (val) => {
	currentPage.value = val;
	getList();
};


const formData = ref({
	planNo: '',
	name: '',
	planBeginTime: null,
	planEndTime: null,
	actualBeginTime: null,
	actualEndTime: null,
	organizationId: '',
	status: '0',
	type: '0'
});

const crudTitle = computed(() => {
	if (popType.value === 1) {
		return '查看';
	} else {
		return isEdit.value ? '编辑' : '新建';
	}
});

const showDetail = ref(false);


// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};
	currentPage.value = 1;
	// currentPage.value = 1
	getList();
};

const procedureOrderList = ref([]);
const wareList = ref([]);
const storageList = ref([]);
const materiaList = ref([]);
const showOutIn = ref(false);
const outInFormRef = ref(null);
const formRef = ref(null);
const outInRules = reactive<FormRules<formRef>>({
	procedureOrderId: [
		{ required: true, message: '请选择工序订单', trigger: 'blur' }
	],
	sourceStorageId: [
		{ required: true, message: '请选择出库库位', trigger: 'blur' }
	],
	targetStorageId: [
		{ required: true, message: '请选择入库库位', trigger: 'blur' }
	],
	batchNo: [
		{ required: true, message: '请选择批次号', trigger: 'blur' }
	]

});
const handleAddConfigLine = () => {
	formData.value.details.push({
		materialId: null,
		materialCount: null,
		batchNo: null
	});
};
const outInSum = async (formEl: FormInstance | undefined) => {
	await formEl.validate((valid, fields) => {
		if (valid) {
			const param = outInForm.value;
			outFatherInfo.value.details = [param];
			outFatherInfo.value.tasks = [param];
			axiosInstance.post('/api/warehouseMaterialTransferOrder/outStock', outFatherInfo.value)
				.then((res) => {
					if (res.code !== 200) {
						ElMessage.warning(res.message);
						return false;
					}
					showOutIn.value = false;
					getList();
				});
		}
	});

};

const outFatherInfo = ref({});
const batchNoList = ref([]);
const outInForm = ref({});
const doOutIn = (row) => {
	const param = JSON.parse(JSON.stringify(row));
	outInForm.value = param;
	// this.materialCount = JSON.parse(JSON.stringify(param.materialCount))
	// 循环列表 找出子单据的父级
	// 提交时只提交父级和该条子单据

	for (const item of paginatedData.value) {
		if (item.children && item.children.length > 0) {
			for (const items of item.children) {
				if (items.id === row.id) {
					outFatherInfo.value = item;
					outInForm.value.targetWarehouseId = item.targetWarehouseId;
					outInForm.value.targetStorageId = item.targetStorageId;
					outInForm.value.sourceWarehouseId = item.sourceWarehouseId;
					outInForm.value.sourceStorageId = item.sourceStorageId;
					wareChange(item.targetWarehouseId, 1);
					wareChangeOut(item.sourceWarehouseId, 1);
				}
			}
		}
	}

	// sourceStorageId 出库库位  targetStorageId 入库库位
	const params = {
		materialId: row.materialId,
		storageId: outInForm.value.sourceStorageId,
		current: 1,
		pageSize: 999999
	};
	axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', params).then(res => {
		if (res.code != 200) {
			ElMessage.error(res.message);
			return false;
		}

		const loop = [];
		for (const item of res.data.records) {
			if (item.materialStatus == 1) {
				loop.push(item);
			}
		}
		batchNoList.value = loop;
	});
	// getWorkNO(row.materialId, outInForm.value.sourceStorageId)
	showOutIn.value = true;
};

const batchNoChange = () => {
	outInForm.value.batch = batchNoList.value.find(item => item.batchNo === outInForm.value.batchNo).batch;

};

const getWorkNO = (mId, sId) => {
	const params = {
		materialId: mId,
		storageId: sId,
		current: 1,
		pageSize: 999999
	};
	axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', params).then(res => {
		if (res.code != 200) {
			ElMessage.error(res.message);
			return false;
		}

		const loop = [];
		for (const item of res.data.records) {
			if (item.materialStatus == 1) {
				loop.push(item);
			}
		}
		batchNoList.value = loop;
	});
};

const handleConfigDelete = (e) => {
	formData.value.details.splice(e, 1);
};


const wareChange = (e, type) => {
	if (!type) {
		formData.value.targetStorageId = null;
	}
	// storageList.value = {}
	axiosInstance.post('/api/basedataStorage/listByPojoPage', {
		warehouseId: e,
		current: 1,
		pageSize: 999999
	})
		.then((res) => {
			if (res.code !== 200) {
				ElMessage.warning(res.message);
				return false;
			}
			storageList.value = res.data.records;
			searchParam.value.targetStorageId = storageList.value.map(item => item.id);
		});
};

const wareChangeOut = (e, type) => {
	if (!type) {
		formData.value.sourceStorageId = null;
		outInForm.value.sourceStorageId = null;
		searchParam.value.sourceStorageId = null;
	}
	// storageList.value = {}
	axiosInstance.post('/api/basedataStorage/listByPojoPage', {
		warehouseId: e,
		current: 1,
		pageSize: 999999
	})
		.then((res) => {
			if (res.code !== 200) {
				ElMessage.warning(res.message);
				return false;
			}
			storageOutList.value = res.data.records;
			searchParam.value.sourceStorageId = storageOutList.value.map(item => item.id);
		});
};

const storageOutList = ref({});

const getOption = () => {
	axiosInstance
		.post('/api/basedataMaterial/getAll', {}).then(res => {
		if (res.code == 200) {
			const list = res.data;
			const loop = [];
			for (const item of list) {
				loop.push(
					{
						value: item.id,
						label: item.materialName
					}
				);
			}
			materiaList.value = loop;
		}
	});
	axiosInstance.post('/api/planProcedureOrder/getAll', {})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			const list = res.data;
			const loop = [];
			for (const item of list) {
				loop.push(
					{
						value: item.id,
						label: item.materialName
					}
				);
			}
			procedureOrderList.value = list;
		});

	axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
		if (res.code !== 200) {
			ElMessage.error(res.message);
			return false;
		}
		wareList.value = res.data;
	});

	// axiosInstance.post('/api/qualitySchemeTask/getPage', {})
	//     .then(res => {
	//       if (res.code !== 200) {
	//         ElMessage.error(res.message);
	//         return false
	//       }
	//       storageList.value = res.data
	//     })
};

const transferTypeFormatter = (row, column, cellValue) => {
	const typeOptions = {
		transfer: '调拔',
		instock: '入库',
		outstock: '出库',
		pick: '备料'
	};
	return typeOptions[cellValue] || '';
};

const getTypeName = (type: string) => {
	const name = typeList.value.find((item: any) => item.value === type);
	return name ? name.label : '';
};

const typeList = ref([
	{ label: '未完成', value: '0' },
	{ label: '已完成', value: '1' }
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

const transferType = ref({ transferType: 'pick' });

// 新建记录
const handleAdd = () => {
	if (formRef.value) {
		formRef.value.resetFields();
	}
	popType.value = 0;
	isEdit.value = false;
	formData.value = {
		details: [{
			materialId: null,
			materialCount: null,
			batchNo: null
		}]
	};
	showCrud.value = true;
};


const popType = ref(0);//0 编辑 1 只读


const doFinish = (row) => {
	ElMessageBox.confirm('是否确认完结?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			axiosInstance.post('/api/warehouseMaterialTransferOrder/finish', { id: row.id })
				.then(res => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('完结成功');
					getList();
				});
		})
		.catch(() => {
			// 处理取消的情况，如果需要的话
		});
};

const formatStatus = (row, column, cellValue) => {
	switch (cellValue) {
		case 1:
			return '待处理';
		case 2:
			return '进行中';
		case 3:
			return '完结';
	}
};

const filterTag = (value: string, row: User) => {
	return row.status == value;
};

// 编辑记录
const
	handleEdit = (row: any, type) => {
		// console.log(row,'czqRow')

		isEdit.value = true;
		formData.value = { ...row };
		axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', { id: row.id }).then(res => {
			if (res.code !== 200) {
				ElMessage.warning(res.message);
				return false;
			}
			formData.value.details = res.data.children;
			formData.value.tasks = res.data.tasks;
			if (type) {
				// 查看详情
				popType.value = type;
				showDetail.value = true;
			} else {
				// 编辑
				popType.value = 0;
				showCrud.value = true;
			}
			// wareChange(e.targetWarehouseId);
		});
	};


// 保存记录
const handleSave = async (formEl: FormInstance | undefined) => {
	await formEl.validate((valid, fields) => {
		if (valid) {

			const param = formData.value;
			if (param.details.length == 0) {
				ElMessage.warning('请选择物料');
				return false;
			}
			for (const item of param.details) {
				if (!item.materialId) {
					ElMessage.warning('请选择物料');
					return false;
				}
				if (!item.materialCount || item.materialCount === 0) {
					ElMessage.warning('请输入数量');
					return false;
				}


			}
			axiosInstance.post('/api/warehouseMaterialTransferOrder/save', { ...param, ...transferType.value })
				.then((res) => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return false;
					}
					showCrud.value = false;
					getList();
				});
		}
	});
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row: any, expandedRows: any[]) => {
	if (expandedRows.includes(row)) {
		rowChildren(row);
	} else {
		// getList();
	}
};

const rowChildren = (row: any) => {
	axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', { id: row.id }).then(res => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		const listGroup = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data.children };
			}
			return item;
		});
		paginatedData.value = listGroup;
	});
	// axiosInstance.post('/api/basedataQualityScheme/getAll', {planId: row.id})
	//     .then(res => {
	//       if (res.code !== 200) {
	//         ElMessage.error(res.message);
	//         return false
	//       }
	//
	//       .value = res.data
	//     });

	// ProductionPlanDetailApi().then((res) => {
	//   if (res.code !== 200) {
	//     ElMessage.warning(res.message);
	//     return false;
	//   }
	//   const listGroup = paginatedData.value.map((item) => {
	//     if (item.id === row.id) {
	//       return {...item, children: res.data.records};
	//     }
	//     return item;
	//   });
	//   paginatedData.value = listGroup;
	// });
};

const pageTotal = ref(0);

// 获取列表
const getList = async () => {
	paginatedData.value = [];
	axiosInstance.post('/api/warehouseMaterialTransferOrder/listByPojoPage', {
		...searchParam.value,
		current: currentPage.value,
		pageSize: pageSize.value,
		...transferType.value
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			paginatedData.value = res.data.records.map((item) => ({
				...item,
				children: [],
				layer: 1,
				_loading: false
			}));
			pageTotal.value = res.data.total;
		});
};

onMounted(() => {
	getList();
	getOption();
});
</script>
<style scoped lang="scss"></style>
